using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;
using Hallenberg.SmartClient.Menu;
using DemoData.Model;
using DemoData;
using Hallenberg.Core;
using Hallenberg.SmartClient.MVC;

namespace MenuDemo.Controllers
{
    [HandleError]
    public class ProductController : Controller
    {
        [MenuItem(MenuDefinition.MainMenu, MenuDefinition.ProductIndex, "MenuProductsTitle", SortIndex = 100)]
        public ActionResult Index()
        {
            this.ViewData["BrowserTitle"] = Properties.Resources.ProductBrowserTitle;
            this.ViewData["Header"] = Properties.Resources.ProductHeader;
            this.ViewData["ProductName"] = Properties.Resources.ProductPageProductName;
            this.ViewData["ProductPrice"] = Properties.Resources.ProductPageProductPrice;

            int productCount = Repository.Products.Get().Count();
            return View(Repository.Products.Get().Skip(productCount - 20).Take(20).ToList());
        }

        public ActionResult Details(int id)
        {
            return View();
        }

        [Authorize(Roles = "Administrator")]
        [MenuItem(MenuDefinition.ProductIndex, MenuDefinition.CreateProduct, "MenuCreateProduct")]
        public ActionResult Create()
        {
            return View();
        }

        //
        // POST: /Product/Create

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Create(Product product)
        {
            try
            {
                Repository.Products.Save(product);
                return RedirectToAction("Index");
            }
            catch(ValidationException validationException)
            {
                validationException.ApplyToModelState(this.ModelState);
                return View();
            }
            catch
            {
                return View();
            }
        }

        //
        // GET: /Product/Edit/5

        public ActionResult Edit(int id)
        {
            return View();
        }

        //
        // POST: /Product/Edit/5

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Edit(int id, FormCollection collection)
        {
            try
            {
                // TODO: Add update logic here

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }
    }
}
